package com.xiaotu.spider.maoyan.pageprocessor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xiaotu.common.exception.SpiderException;
import com.xiaotu.common.exception.SpiderExceptionCode;
import com.xiaotu.common.model.MaoYanBoxofficeModel;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.DateUtils;
import com.xiaotu.common.util.GsonUtils;
import com.xiaotu.common.util.RegexUtils;
import com.xiaotu.common.util.StringUtil;
import com.xiaotu.common.util.UUIDUtils;
import com.xiaotu.server.service.maoyan.MaoYanMovieBasicInfoService;
import com.xiaotu.spider.AUrlPageProcessor;

import us.codecraft.webmagic.Page;

/***
 * 猫眼相关数据：
 * 昨日票房（每天采集）
 * @author Mr.zhang
 *
 */
@Component("MaoYanMovieSupplementYesterdayBoxofficePageProcessor")
public class MaoYanMovieSupplementYesterdayBoxofficePageProcessor extends AUrlPageProcessor {

	
	
	public static final String START_URL = "https://www.baidu.com/";//初始请求任意地址
	
	public static final String BOX_YESTERDAY_URL = "https://box.maoyan.com/promovie/api/box/second" +
            ".json?beginDate=%s";//昨日票房请求
    
	private String startDate = null;
	
	private String endDate = null;
    
	private Object existMap = null;
	
    @Autowired
    private MaoYanMovieBasicInfoService maoYanMovieBasicInfoService;
    
    
    @Override
    public void initRunParams(Map<String, Object> map)
    {
        if(map.get("startDate") != null)
        	this.startDate = map.get("startDate").toString();
        if(map.get("endDate") != null)
        	this.endDate = map.get("endDate").toString();
    }
    
    
	@Override
	public void process(Page page) {
		
		  //获取当前日期
		  String url = page.getRequest().getUrl();
		  String currDateNum = url.substring(url.lastIndexOf("=")+1);
		  String currDate = convertDateToDate(currDateNum);
		  
		  System.out.println(url);
		
		  existMap = null;	
			
		  String json = page.getRawText();
	      if (StringUtils.isEmpty(json))
	          throw new SpiderException(SpiderExceptionCode.DataInvalideException);
	      Map<String, Object> map = GsonUtils.fromJson(json, Map.class);
	      if (map == null || map.isEmpty() || map.get("data") == null)
	          throw new SpiderException(SpiderExceptionCode.DataInvalideException);
			Map<String, Object> dataMap = ((Map<String, Object>) map.get("data"));
			List<Map<String, Object>> movList = (List<Map<String, Object>>) dataMap.get("list");
	      if (movList == null || movList.isEmpty())
	          throw new SpiderException(SpiderExceptionCode.DataInvalideException);
	      this.getMovieExistList(movList);  
			List<MaoYanBoxofficeModel> list = new ArrayList<>();
	      movList.forEach(movMap ->
	      {
	          String dataId = RegexUtils.regexSearch(RegexUtils.REGEX_INTEGER, StringUtil
	                  .nullToString(movMap.get("movieId")));
	          String tvid = "";
	          Map<String,String> realMap = (Map<String,String>)existMap;
	          if(realMap.containsKey(dataId)){
	        	  tvid = realMap.get(dataId) == null?null:realMap.get(dataId).toString();
	          }
	          MaoYanBoxofficeModel maoYanBoxofficeModel = new MaoYanBoxofficeModel(UUIDUtils.getId(),
	        		  tvid,
	                  StringUtil.nullToString(movMap.get("movieName")),
	                  StringUtil.nullToString(movMap.get("boxInfo")).replace("--", "") + "万", // 当日票房
	                  StringUtil.nullToString(movMap.get("sumBoxInfo")), // 总票房
	                  StringUtil.nullToString(movMap.get("showRate")).replace("--", ""), // 排片比
	                  StringUtil.nullToString(movMap.get("splitBoxRate")).replace("--", ""), // 票房百分比
	                  StringUtil.nullToString(movMap.get("showInfo")).replace("--", ""), // 当日场次
	                  StringUtil.nullToString(movMap.get("releaseInfo")).replace("--", ""), // 上映天数
	                  StringUtil.nullToString(dataMap.get("queryDate")), // 上映日期
	                  StringUtil.nullToString(movMap.get("avgSeatView")).replace("--", ""), // 上座率
	                  StringUtil.nullToString(movMap.get("avgShowView")).replace("--", ""), // 场均人次
	                  StringUtil.nullToString(movMap.get("seatRate")).replace("--", ""), // 排座占比
	                  Constants.SiteName.MAOYAN, //网站名称
	                  dataId,
	                  currDate);//网站电影id
	          maoYanBoxofficeModel.setRedisKey(dataId+"_"+currDate);
	          list.add(maoYanBoxofficeModel);
	      });
	      page.putField(MaoYanBoxofficeModel.class.getName(), list);
		
	}
	
	@Override
	protected String[] getStartRequestUrls() {
		
		List<String> list = new ArrayList<String>();
		
		String currDate = startDate;
		
		while(true){
			
			if(currDate.equals(endDate)){
				list.add(String.format(BOX_YESTERDAY_URL, currDate.replaceAll("[-]", "")));
				break;
			}else{
				list.add(String.format(BOX_YESTERDAY_URL, currDate.replaceAll("[-]", "")));
			}
			currDate = DateUtils.getSpecifiedDayAfterDate(currDate,DateUtils
		            .DAY_FORMAT);
		}
		
		return list.toArray(new String[list.size()]);
		
	}

	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}

	@Override
	public String getPageDataType(Page page) {
        return Constants.PageDataType.SEARCH_LIST;
	}
	
	public void getMovieExistList(List<Map<String, Object>> movList){
		try {
			int availableProcessors = Runtime.getRuntime().availableProcessors();
	    	ExecutorService threadPool = Executors.newFixedThreadPool(availableProcessors>1?availableProcessors:1);
	    	ExistClass existClass = new ExistClass(movList);
	    	Future<Object> submit = threadPool.submit(existClass);
			if(null == existMap){
				synchronized (this){
					if(null == existMap){
						existMap = submit.get();
					}
				}
			}
			threadPool.shutdown();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	
	public class DataClass implements Callable<Object>{
		@Override
		public Object call() throws Exception {
			return maoYanMovieBasicInfoService.queryMovieOffLineListByRecordLineTable();
		}
		
	}
	
	
	public class ExistClass extends DataClass {
		
		private List<Map<String, Object>> movList = new ArrayList<Map<String, Object>>();
		
		@Override
		public Object call() throws Exception {
			return maoYanMovieBasicInfoService.queryMovieExistList(movList);
		}
		
		public ExistClass(List<Map<String, Object>> movList){
			this.movList = movList;
		}
		
		public ExistClass(){
			
		}
		
	}
	
	
	@SuppressWarnings({ "unused"})
	private String getStarLevel(List<String> list){
		Double starLevel = 0.0;
		if(list == null || list.size()<0)
		return null;
		for(String str: list){
			if(str.contains("fullstar")){
				starLevel +=1; 
			}else if(str.contains("halfstar")){
				starLevel+=0.5;
			}
		}
		return starLevel+"";
	}
	
	
	private String convertDateStr(String str){
    	String first = str.substring(0,4);
    	String second = str.substring(4, 6);
    	String three = str.substring(6);
    	return first+"-"+second+"-"+three;
    }
	
	
	public String convertDateToDate(String str){
		
		SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
    	String first = str.substring(0,4);
    	String second = str.substring(4, 6);
    	String three = str.substring(6);
    	return first+"-"+second+"-"+three+" "+sdf.format(new Date());
    }
	
	//将指定日期转化为秒数
    public long getSecondsFromDate(String expireDate){
        if(expireDate==null)
            return 0;
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date=null;
        try{
            date=sdf.parse(expireDate);
            return (long)(date.getTime());
            }
        catch(ParseException e)
        {
            e.printStackTrace();
            return 0;
            }
        }
    
//    public static void main(String[] args) {
//    	System.out.println(getSecondsFromDate(convertDateToDate("20190101")));
//	}
    
}
